#include <iostream>

using std::cout;
using std::endl;

class Base
{
public:
    Base(long base = 0)
    : _base(base)
    {
        cout << "Base(long = 0)" << endl;
    }

    void print() const
    {
        cout << "Base::_base = " << _base << endl;
    }

    ~Base()
    {
        cout << "~Base()" << endl;
    }
private:
    long _base;
};

class Derived
: public Base
{
public:
    Derived(long base = 0, long derived = 0)
    : Base(base)
    , _derived(derived)
    {
        cout << "Derived(long = 0, long = 0)" << endl;
    }

    void show() const
    {
        cout << "Derived::_derived = " << _derived << endl;
    }

    ~Derived()
    {
        cout << "~Derived()" << endl;
    }
private:
    long _derived;
};

void test()
{
    Base base(11);
    base.print();

    cout << endl;
    Derived derived(22, 33);
    derived.show();

    cout << endl << "将派生类对象转换为基类对象" << endl;
    base = derived;//1、可以将派生类对象赋值给基类对象
    //Base &operator=(const Base &rhs)
    //const Base &rhs = derived
    /* base.operator=(derived); */
    base.print();

    cout << endl;
    Base &ref = derived;//2、可以将基类的引用绑定到派生类的对象
    ref.print();

    cout << endl;
    Base *pbase = &derived;//3、可以将基类的指针指向派生类对象
    pbase->print();

    cout << endl << "将基类对象转换为派生类对象" << endl;
    Base base2(100);
    base2.print();

    cout << endl;
    Derived derived2(200, 300);
    derived2.show();

#if 0
    cout << endl;
    derived2 = base2;//1、不能将基类对象赋值给派生类对象
    //Derived &operator=(const Derived &rhs)
    //const Derived &rhs = base2;
    /* derived2.operator=(base2); */

    cout << endl;

    //2、不能将派生类的引用绑定到基类的对象
    Derived &dref = base2;//error,

    //3、不能将派生类的指针指向基类的对象
    Derived *pderived2 = &base2;//error
#endif

    //向下转型(不安全的)
    Derived *pderived2 = static_cast<Derived *>(&base2);

    Base *pbase2 = &derived2;
    //向下转型（安全的）
    Derived *pderived3 = static_cast<Derived *>(pbase2);


}

int main(int argc, char **argv)
{
    test();
    return 0;
}

